package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.Utils.JwtUtils;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${admin.username}")
    private String adminUsername;

    @Value("${admin.password}")
    private String adminPassword;
    @Override
    public String login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("password", password);
        User user = getOne(queryWrapper);
        if (user != null) {
            return jwtUtils.generateToken(user.getId(), user.getUsername());
        }
        return null;
    }
    @Override
    public boolean isAdmin(String username) {
        return  adminUsername.equals(username);
    }
    @Override
    public User getUserByCredentials(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username)
                .eq("password", password);
        return getOne(queryWrapper);
    }
    @Override
    public boolean existsUsername(String username) {
        return baseMapper.selectCount(
                new QueryWrapper<User>().eq("username", username)
        ) > 0;
    }
}